<script setup lang="ts">
import {ref, onMounted, computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios'
// 修改状态标签颜色映射
const statusTagType:{[key: number]: string } = {
  0: 'info',   // 待确认
  1: 'primary',// 维修中
  2: 'success' // 已完成
}
// 新增状态文本映射
const statusText:{[key: number]: string } = {
  0: '待确认',
  1: '维修中',
  2: '已完成'
}
// 在script部分添加映射关系
const positionMap:{[key: number]: string } = {
  0: '初级技工',
  1: '中级技工',
  2: '高级技工',
  3: '专家'
}
// 新增技工接口
interface Technician {
  id: number
  name: string
  position: number
}

// 新增技工相关变量
const technicians = ref<Technician[]>([])
const selectedTechnicianLevel = ref<number>(0)
const selectedTechnicianId = ref<number | null>(null)
const estimatedCompletionTime = ref<string>('')
const allTechnicians = ref<Technician[]>([])

// 获取技工列表
const fetchTechnicians = async (serviceTechnician: number) => {
  try {
    const response = await axios.get(`/api/staff/byPosition?position=${serviceTechnician}`)
    technicians.value = response.data.data
    console.log(technicians)
  } catch (error) {
    console.log(error)
    ElMessage.error('获取技工列表失败')
  }
}

interface Order {
  id: number
  orderNumber: number
  userId: number
  username: string
  serviceName: string
  status: number
  formattedAppointmentTime: string
  licensePlate: string
  description: string
  createTime: string,
  staffId: number
}

const orders = ref<Order[]>([])
const selectedStatus = ref<number>(-1)
const filterStatus = ref<number>(-1) // 页面筛选状态
const dialogStatus = ref<number>(-1)
const search = ref('')
const currentOrderId = ref<number | null>(null)
const dialogVisible = ref(false)
const loading = ref(false)

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/appointment/list')
    orders.value = response.data.data.map((order: any) => ({
      ...order,
      // 保持原始状态数据
      status: order.status
    }))
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}
const fetchAllTechnicians = async () => {
  try {
    const response = await axios.get('/api/staff/list')
    allTechnicians.value = response.data.data
  } catch (error) {
    ElMessage.error('获取员工列表失败')
  }
}

// 更新订单状态
const updateOrderStatus = async () => {
  if (!currentOrderId.value) { // 只需检查订单ID
    ElMessage.warning('请选择订单')
    return
  }

  try {
    await axios.put(`/api/appointment/update`, {
      id: currentOrderId.value,
      status: dialogStatus.value,  // 使用对话框中选择的状态
      staffId: selectedTechnicianId.value,
      estimatedCompletion: estimatedCompletionTime.value
    })
    console.log(selectedTechnicianId.value)
    ElMessage.success('状态更新成功')
    await fetchOrders()
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('更新失败')
  }
}
// 删除订单
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确认删除该订单？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await axios.delete(`/api/appointment/delete`, {
      params: { orderId: id }  // 将id作为查询参数传递
    })
    ElMessage.success('删除成功')
    await fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {  // 只有当不是用户取消操作时才显示错误
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  fetchOrders()
  fetchAllTechnicians()
})
</script>

<template>
  <div class="order-management">
    <div class="filter-section">
      <el-radio-group v-model="filterStatus" class="status-group">
        <el-radio-button :label="-1" :value="-1">全部</el-radio-button>
        <el-radio-button :label="0" :value="0">待确认</el-radio-button>
        <el-radio-button :label="1" :value="1">维修中</el-radio-button>
        <el-radio-button :label="2" :value="2">已完成</el-radio-button>
      </el-radio-group>

      <el-input
          v-model="search"
          placeholder="搜索订单号/车牌号"
          style="width: 300px; margin-left: 20px"
          clearable
      />
    </div>

    <el-table
        :data="orders.filter(o =>
  (filterStatus === -1 || o.status === filterStatus) &&  // 确保使用 filterStatus
  (search === '' ||
   o.orderNumber.toString().includes(search) ||
   o.licensePlate.includes(search))
)">
      <el-table-column prop="orderNumber" label="订单号" width="100"/>
      <el-table-column prop="username" label="用户" width="160"/>
      <el-table-column prop="licensePlate" label="车牌号" width="120"/>
      <el-table-column prop="serviceName" label="服务类型" width="120"/>
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="statusTagType[row.status]">
            {{ statusText[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="formattedAppointmentTime" label="预约时间" width="200"/>
      <el-table-column label="服务人员" width="140">
        <template #default="{ row }">
          {{ allTechnicians.find(t => t.id === row.staffId)?.name || '未分配' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="{ row }">
          <el-button size="small"
                     @click="
    dialogVisible = true;
    currentOrderId = row.id;
    selectedTechnicianId = null;
    dialogStatus = row.status;
    estimatedCompletionTime = '';
    fetchTechnicians(row.serviceTechnician)">
            编辑状态
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 状态编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        title="维修任务分配"
        width="600"
    >
      <div class="dialog-content">
        <el-form label-width="120px">
          <el-form-item label="订单状态：">
            <el-select
                v-model="dialogStatus"
                placeholder="选择状态"
                style="width: 100%"
            >
              <el-option
                  v-for="(text, key) in statusText"
                  :key="key"
                  :label="text"
                  :value="Number(key)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="已选择技工等级">
            <el-tag type="info" size="large">
              {{ positionMap[selectedTechnicianLevel] }}
            </el-tag>
          </el-form-item>

          <el-form-item label="分配技工：">
            <el-select
                v-model="selectedTechnicianId"
                placeholder="请选择技工"
                filterable
                style="width: 100%"
            >
              <el-option
                  v-for="t in technicians"
                  :key="t.id"
                  :label="`${t.name} (${positionMap[t.position]})`"
                  :value="t.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="预计完成时间：">
            <el-date-picker
                v-model="estimatedCompletionTime"
                type="datetime"
                placeholder="选择时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateOrderStatus">
          确认分配
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.order-management {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .filter-section {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
  }

  .status-group {
    margin-right: 20px;
  }
}
</style>